package com.uzai.console.service.pyq.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.device.DeviceQuery;
import com.uzai.console.dto.main.main.ProfitDto;
import com.uzai.console.dto.pyq.llygoods.*;
import com.uzai.console.dto.pyq.pyqautoconfig.PyqAutoConfigQuery;
import com.uzai.console.dto.pyq.pyqautoconfig.PyqAutoConfigStatusDto;
import com.uzai.console.dto.pyq.pyqjobdetail.PyqJobDetailQuery;
import com.uzai.console.dto.wechatprivate.devicewechatinfo.DeviceWechatInfoQuery;
import com.uzai.console.entity.DeviceWechatInfo;
import com.uzai.console.entity.PyqAutoConfig;
import com.uzai.console.entity.PyqAutoSend;
import com.uzai.console.entity.PyqDevicePlan;
import com.uzai.console.mapper.DeviceWechatInfoMapper;
import com.uzai.console.mapper.PyqAutoConfigMapper;
import com.uzai.console.mapper.PyqDevicePlanMapper;
import com.uzai.console.mapper.PyqLlyGoodsMapper;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.UzaiBusinessFeignService;
import com.uzai.console.service.feign.dto.LlyGoodsPageDto;
import com.uzai.console.service.pyq.*;
import com.uzai.console.vo.device.DeviceInfoVo;
import com.uzai.console.vo.pyq.llygoods.PyqLlyGoodsUserVo;
import com.uzai.console.vo.pyq.llygoods.PyqLlyGoodsVo;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 朋友圈老林云商品列表
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class PyqLlyGoodsServiceImpl implements PyqLlyGoodsService {

    Logger logger = LoggerFactory.getLogger(PyqLlyGoodsServiceImpl.class);

    @Autowired
    private PyqDevicePlanMapper pyqDevicePlanMapper;
    @Autowired
    private PyqLlyGoodsSyncService pyqLlyGoodsSyncService;
    @Autowired
    private DeviceWechatInfoMapper deviceWechatInfoMapper;
    @Autowired
    private PyqLlyGoodsMapper pyqLlyGoodsMapper;
    @Autowired
    private UzaiBusinessFeignService uzaiBusinessFeignService;
    @Autowired
    private PyqDevicePlanService pyqDevicePlanService;
    @Autowired
    private PyqJobDetailService pyqJobDetailService;
    @Autowired
    private PyqAutoConfigMapper pyqAutoConfigMapper;
    @Autowired
    private DeviceService deviceService;

    /**
     * 查询朋友圈好单库商品列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqLlyGoodsQuery
     * @return null
     */
    public Page<PyqLlyGoodsVo> findPyqLlyGoodsList(PyqLlyGoodsQuery pyqLlyGoodsQuery){

        //远程通过API从推老板商品库上查询
        //返回到页面分页对象
        Page<PyqLlyGoodsVo> pageVo = new Page<>();

        LlyGoodsPageDto llyGoodsPageDto = new LlyGoodsPageDto();
        BeanUtils.copyProperties(pyqLlyGoodsQuery, llyGoodsPageDto);
        if(StringUtils.isNotBlank(pyqLlyGoodsQuery.getAddDay())){
            //推广开始时间
            Integer queryStartTime = com.uzai.common.utils.DateUtil.getStrTime(pyqLlyGoodsQuery.getAddDay() + " 00:00:00");
            llyGoodsPageDto.setQueryStartTime(queryStartTime);
            //推广结束时间
            Integer queryEndTime = com.uzai.common.utils.DateUtil.getStrTime(pyqLlyGoodsQuery.getAddDay() + " 23:59:59");
            llyGoodsPageDto.setQueryEndTime(queryEndTime);
        }
        //推广开始时间
        llyGoodsPageDto.setPromotionStartTime(pyqLlyGoodsQuery.getPromotionStartTime());
        //推广结束时间
        llyGoodsPageDto.setPromotionEndTime(pyqLlyGoodsQuery.getPromotionEndTime());
        //分页信息
        llyGoodsPageDto.setCurrent(pyqLlyGoodsQuery.getCurrent());
        llyGoodsPageDto.setSize(pyqLlyGoodsQuery.getSize());
        llyGoodsPageDto.setOrderByField(pyqLlyGoodsQuery.getOrderByField());
        llyGoodsPageDto.setAsc(pyqLlyGoodsQuery.isAsc());
        llyGoodsPageDto.setStatus(2); //在线
        llyGoodsPageDto.setPlatform(pyqLlyGoodsQuery.getPlatform());
        llyGoodsPageDto.setUser_id(pyqLlyGoodsQuery.getUserId()); //采集来源(会员id)
        llyGoodsPageDto.setMaterialType(pyqLlyGoodsQuery.getMaterialType()); //附件类型
        UzaiRespVo<Page<PyqLlyGoodsVo>> uzaiRespVo =  uzaiBusinessFeignService.goodsSelectByPage(llyGoodsPageDto);
        //logger.info("---调用推老板老林商品库查询--para={},result={}", JSONObject.toJSONString(llyGoodsPageDto),JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo.getCode() == 200){
            Page<PyqLlyGoodsVo> pyqLlyGoodsVoPage =  uzaiRespVo.getData();
            if(pyqLlyGoodsVoPage != null){
                BeanUtils.copyProperties(pyqLlyGoodsVoPage, pageVo);
                pageVo.setRecords(pyqLlyGoodsVoPage.getRecords());
            }
        }

        //今天开始时间
        String today = Tools.getDateMonthDayStrTwo();
        //今天开始时间
        Integer todayStart = DateUtil.getStrTime(today + " 00:00:00");
        //今天结束时间
        Integer todayEnd = DateUtil.getStrTime(today + " 23:59:59");
        if(pageVo.getRecords() != null && pageVo.getRecords().size() > 0){
            for (PyqLlyGoodsVo record : pageVo.getRecords()) {

                //封装今日发送朋友圈数量
                PyqJobDetailQuery pyqJobDetailQuery = new PyqJobDetailQuery();
                pyqJobDetailQuery.setItemTailId(record.getGoodsTailId());
                pyqJobDetailQuery.setQueryStartTime(todayStart);
                pyqJobDetailQuery.setQueryEndTime(todayEnd);
                int count = pyqJobDetailService.findPyqJobDetailCount(pyqJobDetailQuery);
                record.setTodaySendPyqCount(count);
            }
        }

        return pageVo;
    }

    /**
     * 批量发送朋友任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public void batchSendPyqJpb(PyqLlyGoodsJobBatchSendDao pyqLlyGoodsJobBatchSendDao){
        if(pyqLlyGoodsJobBatchSendDao.getDevicePlanId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择设备方案");
        }

        PyqDevicePlan pyqDevicePlan = pyqDevicePlanMapper.selectById(pyqLlyGoodsJobBatchSendDao.getDevicePlanId(), pyqLlyGoodsJobBatchSendDao.getMerId());
        if(pyqDevicePlan == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择的设备方案不存在");
        }

        //检验该设备方案是否能正常发送朋友圈
//        if(!pyqDevicePlanService.validatePyqDevicePlan(pyqDevicePlan)){
//            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该设备方案配置的机器人联盟和pid不能转链");
//        }

        if(pyqDevicePlan.getDeviceModel() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择发送机器人模式");
        }

        //发送模式(页面不填写，则表示都支持)
        List<Integer> materialTypeList = pyqLlyGoodsJobBatchSendDao.getMaterialTypeList();
        if(materialTypeList == null || materialTypeList.size() == 0){
            pyqLlyGoodsJobBatchSendDao.setMaterialTypeList(Lists.newArrayList(2,5));
        }

        //发送朋友圈的机器人列表
        List<Long> deviceUniqueIdList = null;
        if(pyqDevicePlan.getDeviceModel().intValue() == 0){ //发送部分机器人模式
            //验证发送机器人
            deviceUniqueIdList = JSONObject.parseArray(pyqDevicePlan.getDeviceInfo(), Long.class);
        }else if(pyqDevicePlan.getDeviceModel().intValue() ==1){ //全部机器人
            DeviceQuery deviceQuery = new DeviceQuery();
            deviceQuery.setMerId(pyqLlyGoodsJobBatchSendDao.getMerId());
            deviceQuery.setDeviceType(pyqDevicePlan.getDeviceType());
            List<DeviceInfoVo> deviceList = deviceService.findDeviceList(deviceQuery);
            if(deviceList != null && deviceList.size() > 0){
                deviceUniqueIdList = new ArrayList<>();
                for (DeviceInfoVo deviceInfoVo : deviceList){
                    deviceUniqueIdList.add(deviceInfoVo.getId());
                }
            }
        }

        if(deviceUniqueIdList == null || deviceUniqueIdList.size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该设备方案未配置机器人");
        }

        pyqLlyGoodsJobBatchSendDao.setType(pyqLlyGoodsJobBatchSendDao.getType());
        pyqLlyGoodsJobBatchSendDao.setPlatform(pyqLlyGoodsJobBatchSendDao.getPlatform());
        pyqLlyGoodsJobBatchSendDao.setDomain(pyqDevicePlan.getDomain());//赋值域名

        List<Long> idList = pyqLlyGoodsJobBatchSendDao.getIdList();
        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择商品");
        }

        if(idList.size() > 1){ //批量发送，需要设置时间间隔
            if(pyqLlyGoodsJobBatchSendDao.getTimeInterval() == null){
                throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请输入间隔时间");
            }

            if(pyqLlyGoodsJobBatchSendDao.getTimeInterval() < 1 || pyqLlyGoodsJobBatchSendDao.getTimeInterval() > 1440 ){
                throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "间隔时间范围在1~1440分钟之内");
            }
        }

        //后台异步调用批量发送朋友圈接口
        pyqLlyGoodsSyncService.batchAddJobSync(pyqLlyGoodsJobBatchSendDao, deviceUniqueIdList, pyqDevicePlan);

        try{
            Thread.sleep(500);
        }catch (Exception e){

        }
    }

    /**
     * 单个商品发送朋友任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public void sendPyqJpb(PyqLlyGoodsJobSendDao pyqLlyGoodsJobSendDao){
        if(pyqLlyGoodsJobSendDao.getDevicePlanId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择设备方案");
        }

        PyqDevicePlan pyqDevicePlan = pyqDevicePlanMapper.selectById(pyqLlyGoodsJobSendDao.getDevicePlanId(), pyqLlyGoodsJobSendDao.getMerId());
        if(pyqDevicePlan == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择的设备方案不存在");
        }

        //检验该设备方案是否能正常发送朋友圈
//        if(!pyqDevicePlanService.validatePyqDevicePlan(pyqDevicePlan)){
//            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该设备方案配置的机器人联盟和pid不能转链");
//        }

        if(pyqDevicePlan.getDeviceModel() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择发送机器人模式");
        }

        List<Integer> materialTypeList = pyqLlyGoodsJobSendDao.getMaterialTypeList();
        if(materialTypeList == null || materialTypeList.size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择朋友圈发送类型");
        }

        //发送朋友圈的机器人列表
        List<Long> deviceUniqueIdList = null;
        if(pyqDevicePlan.getDeviceModel().intValue() == 0){ //发送部分机器人模式
            //验证发送机器人
            deviceUniqueIdList = JSONObject.parseArray(pyqDevicePlan.getDeviceInfo(), Long.class);
        }else if(pyqDevicePlan.getDeviceModel().intValue() ==1){ //全部机器人
            DeviceQuery deviceQuery = new DeviceQuery();
            deviceQuery.setMerId(pyqLlyGoodsJobSendDao.getMerId());
            deviceQuery.setDeviceType(pyqDevicePlan.getDeviceType());
            List<DeviceInfoVo> deviceList = deviceService.findDeviceList(deviceQuery);
            if(deviceList != null && deviceList.size() > 0){
                deviceUniqueIdList = new ArrayList<>();
                for (DeviceInfoVo deviceInfoVo : deviceList){
                    deviceUniqueIdList.add(deviceInfoVo.getId());
                }
            }
        }

        if(deviceUniqueIdList == null || deviceUniqueIdList.size() == 0){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "该设备方案未配置机器人");
        }

        pyqLlyGoodsJobSendDao.setType(pyqLlyGoodsJobSendDao.getType());
        pyqLlyGoodsJobSendDao.setPlatform(pyqLlyGoodsJobSendDao.getPlatform());
        pyqLlyGoodsJobSendDao.setDomain(pyqDevicePlan.getDomain());//赋值域名

        if(pyqLlyGoodsJobSendDao.getId() == null){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "请选择老林云商品id");
        }

        List<String> imgList = pyqLlyGoodsJobSendDao.getImgList();

        if(imgList != null && imgList.size() > 9){
            throw  new BusinessException(ResponseCode.PARAMETER_EXCEPTION, "图片数量不能大于9张");
        }

        //后台异步调用单个商品发送朋友圈接口
        pyqLlyGoodsSyncService.addJobSync(pyqLlyGoodsJobSendDao, deviceUniqueIdList, pyqDevicePlan);

    }

    /**
     * 查询悠哉精品库悠友圈会员列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqLlyGoodsUserQuery
     * @return null
     */
    public Page<PyqLlyGoodsUserVo> goodsUserFindByPage(PyqLlyGoodsUserQuery pyqLlyGoodsUserQuery){
        //远程通过API从推老板商品库上查询
        //返回到页面分页对象
        Page<PyqLlyGoodsUserVo> pyqLlyGoodsUserVoPage = null;

        UzaiRespVo<Page<PyqLlyGoodsUserVo>> uzaiRespVo =  uzaiBusinessFeignService.goodsUserFindByPage(pyqLlyGoodsUserQuery);
        logger.info("---调用推老板悠哉精品库悠友圈列表查询--para={},result={}", JSONObject.toJSONString(pyqLlyGoodsUserQuery),JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo.getCode() == 200){
            pyqLlyGoodsUserVoPage =  uzaiRespVo.getData();
            if(pyqLlyGoodsUserVoPage != null){
                if(pyqLlyGoodsUserVoPage.getRecords() != null && pyqLlyGoodsUserVoPage.getRecords().size() > 0){
                    for (PyqLlyGoodsUserVo record : pyqLlyGoodsUserVoPage.getRecords()) {
                        //封装今日再推机器人数量
                        Set<Long> deviceUniqueIdSet = new HashSet<>();
                        //查询所有的运营商自动发送任务
                        PyqAutoConfigQuery pyqAutoConfigQuery = new PyqAutoConfigQuery();
                        pyqAutoConfigQuery.setStatus(1); //启动状态
                        pyqAutoConfigQuery.setTypeList(Arrays.asList(2,3,10)); //悠哉精选的都出来
                        pyqAutoConfigQuery.setYzjxGoodsUserId(record.getId());
                        List<PyqAutoConfig> pyqAutoConfigList = pyqAutoConfigMapper.findByList(pyqAutoConfigQuery);
                        if(pyqAutoConfigList != null && pyqAutoConfigList.size() > 0){
                            for (PyqAutoConfig pyqAutoConfig : pyqAutoConfigList) {
                                Long devicePlanId = pyqAutoConfig.getDevicePlanId();
                                PyqDevicePlan pyqDevicePlan = pyqDevicePlanMapper.selectById(pyqAutoConfig.getDevicePlanId(), pyqAutoConfig.getMerId());
                                if(pyqDevicePlan != null){
                                    if(Tools.getInteger(pyqDevicePlan.getDeviceModel()).intValue() == 0){//部分机器人
                                        String deviceInfo = pyqDevicePlan.getDeviceInfo();
                                        try {
                                            List<Long> deviceUniqueIdList = JSONObject.parseArray(deviceInfo, Long.class);
                                            if(deviceUniqueIdList != null && deviceUniqueIdList.size() > 0){
                                                for (Long deviceUniqueId : deviceUniqueIdList) {
                                                    deviceUniqueIdSet.add(deviceUniqueId);
                                                }
                                            }
                                        }catch (Exception e){

                                        }
                                    }else{
                                        //执行分页查询对象
                                        DeviceWechatInfoQuery deviceWechatInfoQuery = new DeviceWechatInfoQuery();
                                        deviceWechatInfoQuery.setMerId(pyqAutoConfig.getMerId());
                                        List<DeviceWechatInfo> deviceWechatInfoList = deviceWechatInfoMapper.findByList(deviceWechatInfoQuery);
                                        if(deviceWechatInfoList != null && deviceWechatInfoList.size() > 0){
                                            for (DeviceWechatInfo deviceWechatInfo : deviceWechatInfoList) {
                                                deviceUniqueIdSet.add(deviceWechatInfo.getId());
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        record.setPromotingDeviceCount(deviceUniqueIdSet.size());
                    }
                }
            }
        }

        return pyqLlyGoodsUserVoPage;
    }

    /**
     * 查询悠哉精品库悠友圈详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param pyqLlyGoodsUserIdDto
     * @return null
     */
    public PyqLlyGoodsUserVo goodsUserFindById(PyqLlyGoodsUserIdDto pyqLlyGoodsUserIdDto){
        PyqLlyGoodsUserVo pyqLlyGoodsUserVo = null;
        UzaiRespVo<PyqLlyGoodsUserVo> uzaiRespVo =  uzaiBusinessFeignService.goodsUserSelectById(pyqLlyGoodsUserIdDto);
        logger.info("---调用推老板悠哉精品库悠友圈详情查询--para={},result={}", JSONObject.toJSONString(pyqLlyGoodsUserIdDto),JSONObject.toJSONString(uzaiRespVo));
        if(uzaiRespVo.getCode() == 200){
            pyqLlyGoodsUserVo =  uzaiRespVo.getData();
            if(pyqLlyGoodsUserVo != null){
                //封装今日再推机器人数量
                Set<Long> deviceUniqueIdSet = new HashSet<>();
                //查询所有的运营商自动发送任务
                PyqAutoConfigQuery pyqAutoConfigQuery = new PyqAutoConfigQuery();
                pyqAutoConfigQuery.setStatus(1); //启动状态
                pyqAutoConfigQuery.setTypeList(Arrays.asList(2,3,10)); //悠哉精选的都出来
                pyqAutoConfigQuery.setYzjxGoodsUserId(pyqLlyGoodsUserVo.getId());
                List<PyqAutoConfig> pyqAutoConfigList = pyqAutoConfigMapper.findByList(pyqAutoConfigQuery);
                if(pyqAutoConfigList != null && pyqAutoConfigList.size() > 0){
                    for (PyqAutoConfig pyqAutoConfig : pyqAutoConfigList) {
                        Long devicePlanId = pyqAutoConfig.getDevicePlanId();
                        PyqDevicePlan pyqDevicePlan = pyqDevicePlanMapper.selectById(pyqAutoConfig.getDevicePlanId(), pyqAutoConfig.getMerId());
                        if(pyqDevicePlan != null){
                            if(Tools.getInteger(pyqDevicePlan.getDeviceModel()).intValue() == 0){//部分机器人
                                String deviceInfo = pyqDevicePlan.getDeviceInfo();
                                try {
                                    List<Long> deviceUniqueIdList = JSONObject.parseArray(deviceInfo, Long.class);
                                    if(deviceUniqueIdList != null && deviceUniqueIdList.size() > 0){
                                        for (Long deviceUniqueId : deviceUniqueIdList) {
                                            deviceUniqueIdSet.add(deviceUniqueId);
                                        }
                                    }
                                }catch (Exception e){

                                }
                            }else{
                                //执行分页查询对象
                                DeviceWechatInfoQuery deviceWechatInfoQuery = new DeviceWechatInfoQuery();
                                deviceWechatInfoQuery.setMerId(pyqAutoConfig.getMerId());
                                List<DeviceWechatInfo> deviceWechatInfoList = deviceWechatInfoMapper.findByList(deviceWechatInfoQuery);
                                if(deviceWechatInfoList != null && deviceWechatInfoList.size() > 0){
                                    for (DeviceWechatInfo deviceWechatInfo : deviceWechatInfoList) {
                                        deviceUniqueIdSet.add(deviceWechatInfo.getId());
                                    }
                                }
                            }
                        }
                    }
                }
                pyqLlyGoodsUserVo.setPromotingDeviceCount(deviceUniqueIdSet.size());
            }
        }

        return pyqLlyGoodsUserVo;
    }
}
